<template>
<section class="personnel-list">
  <!-- start form search -->
  <el-form :inline="true" :model="formInline" label-width="100px" size="small" class="search-form" label-suffix="：">
    <el-form-item label="单位名称">
      <el-select v-model="formInline.recruitUnitId" placeholder="请选择单位" style="width:200px;" 
        filterable clearable>
        <el-option
          v-for="item in unitOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="岗位名称">
      <el-input v-model="formInline.jobName" placeholder="请输入岗位名称" style="width:200px;"></el-input>
    </el-form-item>
<!--    <el-form-item label="部门" prop="deptId">-->
<!--              <el-select-->
<!--                v-model="formInline.deptId"-->
<!--                filterable-->
<!--                remote-->
<!--                clearable-->
<!--                reserve-keyword-->
<!--                placeholder="请输入关键词"-->
<!--                :remote-method="queryDept"-->
<!--                :loading="loadingDept"-->
<!--                @change="getDeptName"-->
<!--                >-->
<!--                <el-option-->
<!--                  v-for="item in deptOptions"-->
<!--                  :key="item.value"-->
<!--                  :label="item.label"-->
<!--                  :value="item.value">-->
<!--                </el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
    <el-form-item>
      <el-button type="primary" icon="el-icon-search" @click="clickFormSearch">查询</el-button>
    </el-form-item>
  </el-form>
  <!-- end form search -->
  <!-- start btn group -->
  <el-row class="table-control">
    <el-col :span="18">
<!--      <el-button icon="el-icon-plus" size="small" type="primary" plain @click="clickAdd">新增职员</el-button>-->
    </el-col>
    <el-col :span="6"></el-col>
  </el-row>
  <!-- end btn group -->
  <!-- start table -->
  <article class="table-data">
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column type="index" label="序号" width="90"></el-table-column>
<!--      <el-table-column prop="id" label="id" width="90"></el-table-column>-->
      <el-table-column prop="recruitUnit.name" label="招聘单位" width="90"></el-table-column>
      <el-table-column prop="jobName" label="岗位名称" width="90"></el-table-column>
      <el-table-column prop="workTime" label="兼职时间" width="90"></el-table-column>
      <el-table-column prop="location" label="地点" width="90"></el-table-column>
      <el-table-column prop="label" label="兼职标签" width="120"></el-table-column>
      <el-table-column prop="detail" label="岗位描述" width="70"></el-table-column>
      <el-table-column prop="requirement" label="岗位要求" width="120"></el-table-column>
      <el-table-column prop="salaryTreatment" label="薪资待遇" width="100"></el-table-column>
      <el-table-column prop="status" label="岗位状态" width="200" :formatter="formatStatus"></el-table-column>
      <el-table-column prop="needResumeAttachment" label="是否需要简历附件" width="100"></el-table-column>
      <el-table-column prop="wechat" label="WeChat" width="100"></el-table-column>
      <el-table-column prop="creator" label="创建人" align="center" width="150"></el-table-column>
      <el-table-column prop="create_time" label="创建日期"  align="center" width="180" sortable></el-table-column>
      <el-table-column prop="updator" label="更新人" align="center" width="100"></el-table-column>
      <el-table-column prop="update_time" label="更新时间" align="center" width="180"></el-table-column>
<!--      <el-table-column prop="status" label="状态" width="90">-->
<!--        <template slot-scope="scope">-->
<!--          <el-tag effect="dark" :type="scope.row.status === '0' ? 'success' : 'warning'" size="mini">{{scope.row.status | changeToText1}}</el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->


      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button type="danger" @click="clickDelete(scope.row)" size="mini" plain icon="el-icon-delete" circle title="删除"></el-button>
          <el-button size="mini" @click="clickEdit(scope.row)" circle icon="el-icon-edit" title="编辑"></el-button>
        </template>
      </el-table-column>
    </el-table>
  </article>
  <!-- end table -->
  <!-- start pagination -->
  <el-pagination :current-page="1" :page-sizes="[10, 20, 30, 40]" :page-size="1" layout="total, sizes, prev, pager, next, jumper" :total="4" class="table-pagination">
  </el-pagination>
  <!-- end pagination -->
  <!-- start 新增模态窗 -->
  <el-dialog :title="dialogType === 'add' ? '新增岗位' : '编辑岗位'" :visible.sync="modalAdd" width="600px">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
      <el-form-item label="岗位名称" prop="jobName">
        <el-input v-model="ruleForm.jobName" placeholder="请输入岗位名称"></el-input>
      </el-form-item>
      <el-form-item label="工作时间" prop="workTime">
        <el-input v-model="ruleForm.workTime" placeholder="请输入工作时间"></el-input>
      </el-form-item>
      <el-form-item label="工作地点" prop="location">
        <el-input v-model="ruleForm.location" placeholder="请输入工作地点"></el-input>
      </el-form-item>
      <el-form-item label="标签" prop="labelList">
        <el-select v-model="ruleForm.labelList" 
          multiple 
          placeholder="请选择标签"
          @change="handleLabelChange">
          <el-option
            v-for="item in labelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="岗位描述" prop="detail">
        <el-input type="textarea" v-model="ruleForm.detail" placeholder="请输入岗位描述"></el-input>
      </el-form-item>
      <el-form-item label="岗位要求" prop="requirement">
        <el-input type="textarea" v-model="ruleForm.requirement" placeholder="请输入岗位要求"></el-input>
      </el-form-item>
      <el-form-item label="薪资待遇" prop="salaryTreatment">
        <el-input v-model="ruleForm.salaryTreatment" placeholder="请输入薪资待遇"></el-input>
      </el-form-item>
      <el-form-item label="是否需要简历" prop="needResumeAttachment">
        <el-select v-model="ruleForm.needResumeAttachment" placeholder="请选择">
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="modalAdd = false">取 消</el-button>
      <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
    </div>
  </el-dialog>
  <!-- end 新增模态窗 -->
</section>
</template>

<script>
export default {
  name: 'PersonnelList', //人员管理
  data() {
    return {
      modalAdd: false,
      pageCurrent: 1,//默认页码
      pageSize: 50,//默认页的尺寸
      count: 0,//数据的总记录数
      loadingDept:false,
      deptOptions:[],
      roleOptions:[],
      unitOptions: [], // 单位选项列表
      formInline: {
        recruitUnitId: null,  // 改为 null，确保传递数字或 null
        jobName: '',       // 岗位名称
      },
      labelOptions: [
        { value: 1, label: '计算机' },
        { value: 2, label: 'Java' },
        { value: 3, label: '日结' },
        { value: 4, label: '骑手' },
        { value: 10, label: '包吃' },
        { value: 11, label: '有提成' },
        { value: 12, label: '完结工' }
      ],
      ruleForm: {
        id: '',                  // 岗位信息id
        recruitUnitId: '',       // 招聘单位id
        jobName: '',            // 岗位名称
        workTime: '',           // 兼职时间
        location: '',           // 地点
        label: '',              // 用于存储格式化后的标签字符串 {1}{2}
        labelList: [],          // 用于存储选中的标签值数组
        detail: '',             // 岗位描述
        requirement: '',        // 岗位要求
        salaryTreatment: '',    // 薪资待遇
        status: '',             // 岗位状态
        needResumeAttachment: '', // 是否需要简历附件
      },
      rules: {
        jobName: [{
          required: true,
          message: '请输入岗位名称',
          trigger: 'blur'
        }],
        workTime: [{
          required: true,
          message: '请输入兼职时间',
          trigger: 'blur'
        }],
        location: [{
          required: true,
          message: '请输入工作地点',
          trigger: 'blur'
        }],
      },
      tableData: [],
      dialogType: 'add'
    }
  },
  methods: {
    formatStatus(row) {
      if (row.status === '1'){
        return '已发布';
      }else if (row.status === '2'){
        return '已关闭';
      }else if (row.status === '3'){
        return '已删除';
      }
    },
    clickAdd() {
      this.dialogType = "add";
      this.modalAdd = true;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const url = this.dialogType === 'add' ? '/jobInfo/add' : '/jobInfo/edit';
          // 创建提交数据的副本，避免修改原始数据
          const submitData = {
            ...this.ruleForm,
            label: JSON.stringify(this.ruleForm.labelList)  // 将标签数组转换为JSON字符串
          };
          
          this.$axios.post(url, submitData)
            .then(res => {
              if (res.code === 200) {
                this.$message.success(this.dialogType === 'add' ? '添加成功' : '更新成功');
                this.modalAdd = false;
                // 刷新列表
                this.queryList({
                  pageSize: this.pageSize,
                  pageCurrent: this.pageCurrent
                });
              } else {
                this.$message.error(res.msg || (this.dialogType === 'add' ? '添加失败' : '更新失败'));
              }
            })
            .catch(error => {
              console.error('提交表单出错:', error);
              this.$message.error('操作失败，请稍后重试');
            });
        } else {
          return false;
        }
      });
    },
    async clickEdit(params) {
      console.log("点击编辑按钮");
      this.dialogType = "edit";
      console.log("编辑传入的参数", params);
      try {
        const res = await this.$axios.get('/jobInfo/getById', {
          params: {
            id: params.id
          }
        });
        console.log("后端返回的数据:", res.data);
        if (res.code === 200) {
          this.resetEdit();
          // 用返回的数据填充表单
          const jobInfo = res.data;
          this.ruleForm = {
            id: jobInfo.id,
            recruitUnitId: jobInfo.recruitUnitId,
            jobName: jobInfo.jobName,
            workTime: jobInfo.workTime,
            location: jobInfo.location,
            label: jobInfo.label,
            labelList: this.parseLabelString(jobInfo.label),
            detail: jobInfo.detail,
            requirement: jobInfo.requirement,
            salaryTreatment: jobInfo.salaryTreatment,
            status: jobInfo.status,
            needResumeAttachment: jobInfo.needResumeAttachment
          };
          // 显示对话框
          this.modalAdd = true;
          console.log("填充后的表单数据:", this.ruleForm);
        } else {
          this.$message.error(res.msg || "获取岗位信息失败");
        }
      } catch (error) {
        console.error("获取岗位信息出错:", error);
        this.$message.error("获取岗位信息失败");
      }
    },
    resetEdit() {
      this.ruleForm = {
        id: '',
        recruitUnitId: '',
        jobName: '',
        workTime: '',
        location: '',
        label: '',
        labelList: [],
        detail: '',
        requirement: '',
        salaryTreatment: '',
        status: '',
        needResumeAttachment: ''
      };
    },
    //搜索
    clickFormSearch() {
      const params = {
        pageSize: this.pageSize,
        pageCurrent: this.pageCurrent,
        jobName: this.formInline.jobName
      };
      if (this.formInline.recruitUnitId) {
        params.recruitUnitId = this.formInline.recruitUnitId;
      }
      this.queryList(params);
    },
    queryList(data) {
      console.log("发送的查询参数：", data);  // 添加日志
      this.$axios.post("/jobInfo/list", data).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data.records;
          console.log('查询结果：', this.tableData);
          this.count = res.total;
          this.pageCurrent = res.current;
        } else {
          this.$message.error("查询失败!");
        }
      });
    },
    clickDelete(row) {
      this.$confirm('此操作将永久删除此项, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          console.log(row);
          this.deletePerson(row);
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    deletePerson(data){
        this.$axios.delete("/jobInfo/delete/" + data.id).then((res) => {
        if (res.code == 200) {
          this.$message.success("删除成功");
          if (
            (this.pageCurrent * this.pageSize - this.count) % this.pageSize ==
            this.pageSize - 1
          ) {
            this.pageCurrent -= 1;
          }
          this.queryList({
            pageSize: this.pageSize,
            pageCurrent: this.pageCurrent,
          });
        }else{
          this.$message.error(res.msg || "删除失败");
        }
      });
    },
    queryDept(){
      var list = [];//接收返回的数据
      var states = [];
      console.log("222222222")
      let a ={};
          this.loadingDept = true;//从远程获取数据
          this.$axios.post("/proDept/list",a).then((res) => {
            if (res.code == 200) {
              states = res.data.records;
              list = states.map(item => {
                console.log('33333344'+item.name);
                return {
                   value: `${item.id}`,
                    label: `${item.name}` };
              });
              setTimeout(() => {
                this.loadingDept = false;
                this.deptOptions = list;
              }, 200);
              console.log(list);
            }
          });
    },
    queryRole(params){
      console.log('ppppp'+params);
      if(params == null){
        params={}
      }
      var list = [];//接收返回的数据
      var states = [];
       console.log("222222222")
      // let a ={};
          //this.loadingDept = true;//从远程获取数据
          this.$axios.post("/proRole/list",params).then((res) => {
            if (res.code == 200) {
              states = res.data.records;
              list = states.map(item => {
                return {
                   value: `${item.id}`,
                    label: `${item.name}` };
              });
              setTimeout(() => {
                //this.loadingDept = false;
                this.roleOptions = list;
              }, 200);
            }
          });
    },
    getDeptName(deptName){
      let deptOption = {};
      deptOption = this.deptOptions.find((item) => {
        return item.value == deptName;
      });
      this.ruleForm.deptName = deptOption.label;
    },
    // 获取单位列表
    getUnitOptions() {
      this.$axios.post("/recruitUnit/list", {
        pageSize: 1000,  // 获取足够多的选项
        pageCurrent: 1
      }).then(res => {
        if (res.code === 200) {
          this.unitOptions = res.data.records;
        }
      });
    },
    // 处理标签选择变化
    handleLabelChange(values) {
      // 直接保存选中的值数组
      this.ruleForm.label = JSON.stringify(values);
      this.ruleForm.labelList = values;
    },
    // 修改解析方法
    parseLabelString(labelStr) {
      if (!labelStr) return [];
      try {
        // 尝试解析JSON字符串
        return JSON.parse(labelStr);
      } catch (e) {
        // 如果解析失败，尝试解析旧格式 {1}{2}
        return labelStr.split('}{').map(item => {
          return parseInt(item.replace(/{|}/g, ''));
        });
      }
    },
  },
  filters: {
    changeToText1(value) {
      if (value == '0')
        return '正常'
      else if (value == '1') {
        return '停用'
      }
    },
    changeToText3(value) {
      if (value == '0')
        return '销售部'
      else if (value == '1') {
        return '设计部'
      }else if (value == '2') {
        return '生产部'
      }
      else if (value == '3') {
        return '财务部'
      }
      else if (value == '4') {
        return '总经办'
      }
    },
  },
  mounted() {
    this.queryList({
      pageSize: this.pageSize,
      pageCurrent: this.pageCurrent,
    });
    this.queryDept();
    this.queryRole();
    this.getUnitOptions();  // 获取单位选项
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
.personnel-list {}
</style>
